package leetcode.easy;

/**
 * ClassName: $463_IslandPerimeter
 * Description:
 * date: 2022-02-17 17:34
 *
 * @author liyifan
 */
public class $463_IslandPerimeter {
    int rows;
    int cols;
    public int islandPerimeter(int[][] grid) {
        int land = 0;
        int border = 0;
        rows = grid.length;
        cols = grid[0].length;

        for (int i = 0;i < rows;i++) {
            for (int j = 0;j < cols;j++) {
                if (grid[i][j] == 1) {
                    land++;
                    // 判断接壤

                    if (isArea(grid, i + 1, j) && grid[i + 1][j] == 1){
                        border++;
                    }

                    if (isArea(grid, i, j + 1) && grid[i][j + 1] == 1){
                        border++;
                    }
                }
            }
        }

        return 4 * land - 2 * border;
    }

    public int islandPerimeterDFS(int[][] grid) {
        rows = grid.length;
        cols = grid[0].length;
        int res = 0;
        for (int i = 0;i < rows;i++) {
            for (int j = 0;j < cols;j++) {
                if (grid[i][j] == 1) {
                    res += dfs(grid, i, j);
                }
            }
        }

        return 0;
    }

    public int dfs(int[][] grid, int r, int c){
        if (!isArea(grid, r, c))
            return 1;
        if (grid[r][c] == 0)
            return 1;
        grid[r][c] = 2;
        return dfs(grid, r - 1, c) + dfs(grid, r + 1, c) + dfs(grid, r, c - 1) + dfs(grid, r, c + 1);
    }

    public boolean isArea(int[][] grid, int r, int c){
        return r >= 0 && r < rows && c >= 0 && c < cols;
    }
}
